package com.example.seh.home.secondhand;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.seh.R;
import com.example.seh.chat.ChatActivity;
import com.example.seh.chat.Msg;
import com.example.seh.constant.Constant;
import com.example.seh.home.SelectActivity;
import com.example.seh.home.select.Bean;
import com.example.seh.util.ChatUtil;
import com.example.seh.util.ImgUtil;
import com.example.seh.util.LoginActivity;
import com.example.seh.util.LoginUtil;
import com.example.seh.util.UserMsg;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.indicator.CircleIndicator;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class GoodsDetailActivity extends AppCompatActivity {
    private Banner banner;
    private TextView name, dept, price, content;
    private Button back, buyBtn, business;
    private List<Integer> bannerData;
    private List<Bitmap> bannerImg;
    private GoodsDTO goods;
    private Bean beans;
    private List<String> imgs = new ArrayList<>();
    private Bitmap bitmapToBuy;
    private Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    bannerImg = (List<Bitmap>) msg.obj;
                    banner.setAdapter(new BannerImageAdapter<Bitmap>(bannerImg) {
                        @Override
                        public void onBindView(BannerImageHolder holder, Bitmap data, int position, int size) {
                            holder.imageView.setImageBitmap(data);
                        }
                    });
                    // 开启循环轮播
                    banner.isAutoLoop(true);
                    banner.setIndicator(new CircleIndicator(getApplicationContext()));
                    banner.setScrollBarFadeDuration(1000);
                    // 设置指示器颜色(TODO 即选中时那个小点的颜色)
                    banner.setIndicatorSelectedColor(Color.GREEN);
                    // 开始轮播
                    banner.start();
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail);
        initData();
        getActivityDatas();
        //----------------------轮播图-------------------
        initBannerData();//初始化轮播图数据
//        banner.setAdapter(new BannerImageAdapter<Integer>(bannerData) {
//            @Override
//            public void onBindView(BannerImageHolder holder, Integer data, int position, int size) {
//                holder.imageView.setImageResource(data);
//            }
//        });//轮播图adapter



        setListeners();


    }

    private void setListeners() {
        content.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), SelectActivity.class);
                startActivity(intent);
            }
        });

        //----------------------返回键-------------------
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //----------------------点击购买-------------------
        buyBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Constant.isLogin) {
                    Intent intent = new Intent(GoodsDetailActivity.this, GoodsBuyActivity.class);
                    intent.putExtra("goods", goods);
                    startActivity(intent);
                } else {
                    Toast.makeText(getApplicationContext(), "请先进行登录", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(GoodsDetailActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            }
        });

        business.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Constant.isLogin) {
                    Intent intent = new Intent(GoodsDetailActivity.this, ChatActivity.class);
                    intent.putExtra("buniess",goods);
                    Log.e("buy",goods.toString());
                    if (goods.getUserDTO().getPic() != null) {
                        ChatUtil.youAvatar = goods.getUserDTO().getPic();
                    }
                    if (UserMsg.userDTO.getPic() != null) {
                        ChatUtil.myAvatar = UserMsg.userDTO.getPic();
                    }
                    addChat();
                    startActivity(intent);
                } else {
                    Toast.makeText(getApplicationContext(), "请先进行登录", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(GoodsDetailActivity.this, LoginActivity.class);
                    startActivity(intent);
                }

            }
        });
    }

    private void addChat() {
        Log.e("chat","自动回复");
        String txt = "自动回复:你好!";
//        Message message = new Message();
//        message.what = 2;
//        message.obj = txt;
//        com.example.seh.chat.ChatActivity.handler.sendMessage(message);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String nowTime  = formatter.format(curDate);

        ChatUtil.msgList.add(new Msg(goods.getUserDTO().getUserId(), UserMsg.userDTO.getUserId(), txt, null, Msg.MSG));
        OkHttpClient okHttpClient = new OkHttpClient();
        JSONObject object = new JSONObject();
        try {
            object.put("fromId", goods.getUserDTO().getUserId());
            object.put("toId", UserMsg.userDTO.getUserId());
            object.put("message", txt);
            object.put("msgOrImgType", Msg.MSG);
            object.put("sendTime", nowTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType type = MediaType.parse("application/json;charset=utf-8");
        Log.e("chat", object.toString());
        RequestBody body = RequestBody.create(type, "" + object.toString());

        Request request = new Request.Builder()
                .url(Constant.SENDMSG)
                .post(body)
                .build();
        Log.e("chat","66666666666666666666");
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("chat","消息保存失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e("chat",result);
                if ("添加成功".equals(result)) {
                    Log.e("chat","消息保存成功");
                }
            }
        });
    }

    private void getActivityDatas() {
        Intent intent = getIntent();
        goods= (GoodsDTO) intent.getSerializableExtra("goods");
        beans = (Bean) intent.getSerializableExtra("searchGoods");
        if (goods!=null){
            name.setText(goods.getGoodsName());
            dept.setText(goods.getGoodsDesc());
            price.setText(goods.getGoodsPrice() + "");
            if (goods.getGoodsPic() != null) {
                imgs = Arrays.asList(goods.getGoodsPic().split(";"));
                Log.e("img",imgs.toString());
            }
        }
        if (beans!=null){
            name.setText(beans.getTitle());
            dept.setText(beans.getContent());
            price.setText(beans.getPrice()+"");
            if (beans.getGoodsPic()!=null){
                imgs = Arrays.asList(beans.getGoodsPic().split(";"));
            }
        }

    }

    private void initBannerData() {
//        bannerData = new ArrayList<>();
//        bannerData.add(R.drawable.banner1);
//        bannerData.add(R.drawable.banner2);
//        bannerData.add(R.drawable.banner3);
//        bannerData.add(R.drawable.banner4);




        new Thread(new Runnable() {
            @Override
            public void run() {
                StrictMode.setThreadPolicy(new
                        StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
                StrictMode.setVmPolicy(
                        new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
                Log.e("img","new thread");
                try {
                    List<Bitmap> bannerImgByThread = new ArrayList<>();
                    for (int i = 0; i < imgs.size(); i++) {
                        bannerImgByThread.add(ImgUtil.stringToBitmap(imgs.get(i)));
                    }
                    
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = bannerImgByThread;
                    handler.sendMessage(msg);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }).start();

    }

    private void initData() {
        name = findViewById(R.id.goods_detail_name);
        dept = findViewById(R.id.goods_detail_dept);
        business = findViewById(R.id.goods_detail_business);
        banner = findViewById(R.id.goods_detail_banner);
        price = findViewById(R.id.goods_detail_price);
        back = findViewById(R.id.back);
        buyBtn = findViewById(R.id.buy);
        content = findViewById(R.id.select_goods_detail);
    }
}